<template>
  <div id="BookMark">
    <a-card title="点击书签跳转至书签范围" style="width: 300px" size="small">
      <a slot="extra" href="#" title="关闭" @click="onClose">
        <a-icon type="close" />
      </a>

      <a-input-group compact>
        <a-input placeholder="输入书签名" size="small" v-model="bookname">
          <icon-font
            slot="addonAfter"
            type="icon-tianjia"
            @click="addBookMark"
          />
        </a-input>
      </a-input-group>
      <div
        class="booktag"
        style="margin-top: 10px"
        v-show="bookmarklist && bookmarklist.length"
      >
        <a-tag
          style="margin-top: 10px"
          :color="color()"
          v-for="item in bookmarklist"
          :key="item.id"
          @click="toMapBookLocation(item.id)"
          closable
          @close="() => removeThisBookMark(item.id)"
          >{{ item.name }}
        </a-tag>
      </div>
    </a-card>
  </div>
</template>

<script>
import { Icon } from "ant-design-vue";
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: "./iconfont/iconfont.js",
});
import L from "leaflet";
import services from "@/services/api.js";
export default {
  data() {
    return {
      IconFont,
      bookname: null,
      bookmarklist: null,
    };
  },
  computed: {
    map() {
      return this.$store.state.map;
    },
    checkedLayers() {
      return this.$store.state.checkedLayers;
    },
    userName() {
      return this.$store.state.userName;
    },
  },
  components: {
    IconFont,
  },
  methods: {
    color() {
      return (
        "#" +
        ("00000" + ((Math.random() * 0x1000000) << 0).toString(16)).substr(-6)
      );
    },
    onClose() {
      this.$parent.isBookMark = false;
    },
    toMapBookLocation(id) {
      console.log(id);
      let bookitem = this.bookmarklist.filter((item) => item.id == id)[0];
      if (bookitem && bookitem.data) {
        console.log("要展开的书签", bookitem);
        let corner1 = L.latLng(
            bookitem.data.bounds._northEast.lat,
            bookitem.data.bounds._northEast.lng
          ),
          corner2 = L.latLng(
            bookitem.data.bounds._southWest.lat,
            bookitem.data.bounds._southWest.lng
          ),
          bounds = L.latLngBounds(corner1, corner2);
        this.map.flyToBounds(bounds);
      } else {
        this.$message.warning("此书签未记录到地图数据");
      }
    },
    //移除记录from浏览器缓存
    removeThisBookMarkFromBrower(removedTagid) {
      let list = this.bookmarklist.filter((item) => item.id !== removedTagid);
      this.bookmarklist = list;
      localStorage.setItem("MapBookmarks", JSON.stringify(this.bookmarklist));
      this.$message.success("移除成功");
    },
    removeThisBookMark(removedTagid) {
      if (!this.userName) {
        this.removeThisBookMarkFromBrower(removedTagid);
        return;
      }
      // let list = this.bookmarklist.filter((item) => item.id !== removedTagid);
      let willRemoveOne = this.bookmarklist.filter(
        (item) => item.id == removedTagid
      );
      let param = {
        id: willRemoveOne[0].id,
      };
      services.removeBookMark(param).then((res) => {
        res.success == true
          ? (this.queryBookMark(), this.$message.success("移除成功"))
          : (this.$message.warning("移除失败"),
            (this.bookmarklist = [...this.bookmarklist]));
      });
    },
    //保存至浏览器
    addBookMarkToBrower() {
      let queryBookMark = this.bookmarklist.filter(
        (item) => item.name == this.bookname
      )[0];
      if (queryBookMark) {
        this.$message.info("存在同名书签，将更新书签记录至本地");
        this.queryBookMark.data = this.toaddMark.data;
        localStorage.setItem("MapBookmarks", JSON.stringify(this.bookmarklist));
      } else {
        this.bookmarklist.push(this.toaddMark);
        localStorage.setItem("MapBookmarks", JSON.stringify(this.bookmarklist));
        this.$message.success("您暂未登录，已成功添加记录至本地缓存");
      }
    },
    addBookMark() {
      if (this.bookname && this.bookname !== "") {
        this.bookname = this.bookname.replace(/\s+/g, "");
        this.toaddMark = {
          id: this.bookmarklist.length,
          name: this.bookname,
          data: {
            center: this.map.getCenter(),
            zoom: this.map.getZoom(),
            bounds: this.map.getBounds(),
            size: this.map.getSize(),
            openlayers: this.checkedLayers,
          },
        };
        console.log("书签信息", this.toaddMark);
        if (!this.userName) {
          this.addBookMarkToBrower();
          //this.$message.info("您未登录,暂无法使用此功能");
          return;
        }

        let param = {
          data: JSON.stringify(this.toaddMark),
          userName: this.userName,
          name: "书签",
        };
        services.savebookMark(param).then((res) => {
          res.success == true
            ? (this.queryBookMark(), this.$message.success("添加成功"))
            : this.$message.error("添加失败");
        });
        // let queryBookMark = this.bookmarklist.filter(
        //   (item) => item.name == this.bookname
        // )[0];
        // if (queryBookMark) {
        //   this.$message.info("存在同名书签，将更新书签记录");
        //   services.savebookMark(param).then((res) => {
        //     res.success == true
        //       ? ((this.queryBookMark.data = this.toaddMark.data),
        //         this.$message.success("更新成功"))
        //       : this.$message.error("更新失败");
        //   });
        // } else {

        // }
      } else {
        this.$message.info("书签名不能为空");
        return;
      }
    },

    async queryBookMark() {
      this.bookmarklist = [];
      let param = {
        userName: this.userName,
        pageNo: 1,
        pageSize: 100,
      };
      if (!this.userName) {
        this.bookmarklist = JSON.parse(localStorage.getItem("MapBookmarks"));
        if (this.bookmarklist == undefined || this.bookmarklist == null) {
          this.bookmarklist = [];
        }
        this.bookmarklist.length
          ? this.$message.info("您未登录,已帮您获取本地保存记录")
          : "";
        return;
      }
      await services.querybookMark(param).then((res) => {
        let userNameBookList = res.result.records.filter(
          (item) =>
            item.userName == this.userName &&
            item.name &&
            item.name.indexOf("书签") > -1
        );
        let aBookMark;
        userNameBookList.map((item) => {
          item.data != ""
            ? ((aBookMark = JSON.parse(item.data)),
              (aBookMark.id = item.id),
              this.bookmarklist.push(aBookMark))
            : "";
        });
      });
    },
    async getUerName() {
      await services
        .getUserName()
        .then((res) => {
          console.log("用户信息", res);
          res.userName && res.userName != null && res.userName !== "GUEST"
            ? (this.$store.commit("setUserName", res.userName),
              this.queryBookMark())
            : this.queryBookMark();
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  mounted() {
    this.getUerName();
  },
};
</script>

<style></style>
